package com.wss.module.user.ui.account.mvp.model;

import com.wss.common.base.mvp.BaseModel;
import com.wss.common.bean.User;

import com.wss.common.net.Api;
import com.wss.common.net.NetworkManage;
import com.wss.common.net.request.RequestParam;
import com.wss.common.utils.JsonUtils;
import com.wss.module.user.ui.account.mvp.contract.RegisterContract;

import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;
import io.reactivex.Observable;
import ohos.aafwk.ability.ILifecycle;
import ohos.aafwk.ability.Lifecycle;

/**
 * Describe：注册Module
 * Created by 吴天强 on 2018/11/13.
 */
public class RegisterModel extends BaseModel implements RegisterContract.Model {


    public RegisterModel(Lifecycle lifecycleOwner) {
        super(lifecycleOwner);
    }

    @Override
    public void register(String userName, String password, SimpleCallBack<User> callBack) {
        HttpParams params = new HttpParams();
        params.put("username", userName);
        params.put("password", password);
        params.put("repassword", password);
        NetworkManage.createPostForm()
                .request(Api.REGISTER, params, new CallBack<String>() {
                    @Override
                    public void onStart() {
                        callBack.onStart();
                    }

                    @Override
                    public void onCompleted() {
                        callBack.onCompleted();
                    }

                    @Override
                    public void onError(ApiException e) {
                        callBack.onError(e);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("==== result : " + s);
                        int errorCode = JsonUtils.getInt(s, "errorCode");
                        if (errorCode == 0) {
                            User user = JsonUtils.getObject(JsonUtils.getString(s, "data"), User.class);
                            callBack.onSuccess(user);
                        } else {
                            String errorMsg = JsonUtils.getString(s, "errorMsg");
                            callBack.onError(new ApiException(new Throwable(errorMsg), errorCode));

                        }
                    }
                });
    }
}
